﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Thor.Common;
using Thor.Configuration;

namespace Thor.Common
{
    public class MessageHelper
    {
        #region fields

        private static ConfigurationSettings _configSettings = new ConfigurationSettings();
        private static string _ApplicationNameKey = ConfigurationSettings.ApplicationNameKey;
        private static string _ApplicationNameValue = ConfigurationSettings.ApplicationNameValue;
        private static string _ConnectionStringKey = ConfigurationSettings.ConnectionStringKey;
        private static string _ConnectionStringValue = ConfigurationSettings.ConnectionStringValue;
        private static string _MessageRepositoryAssembly = AppDomain.CurrentDomain.BaseDirectory + ConfigurationSettings.MessageRepositoryAssembly;
        private static string _MessageRepositoryType = ConfigurationSettings.MessageRepositoryType;
        private static string _QueueAddressKey = ConfigurationSettings.QueueAddressKey;
        private static string _QueueAddressValue = ConfigurationSettings.QueueAddressValue;

        #endregion

        #region constructors

        private MessageHelper() { }

        #endregion

        #region properties

        private static ConfigurationSettings ConfigurationSettings
        {
            get
            {
                if (_configSettings == null)
                    _configSettings = new ConfigurationSettings();

                return _configSettings;
            }
        }

        #endregion

        #region methods

        public static Message GetMessage()
        {
            return GetMessageManager().Fetch();
        }

        public static void DeleteMessage(Message message)
        {
            GetMessageManager().Delete(message);
        }

        public static void Clear()
        {
            GetMessageManager().Clear();
        }

        private static Dictionary<string, object> GetMessageRepositoryParameters()
        {
            var parameters = new Dictionary<string, object>();
            parameters.Add(_ConnectionStringKey, _ConnectionStringValue);
            parameters.Add(_QueueAddressKey, _QueueAddressValue);
            return parameters;
        }

        private static IMessageRepository GetMessageRepository(Dictionary<string, object> parameters)
        {
            return MessageManager.GetRepository(_MessageRepositoryAssembly, _MessageRepositoryType, parameters);
        }

        public static MessageManager GetMessageManager()
        {
            var parameters = GetMessageRepositoryParameters();
            var repository = GetMessageRepository(parameters);
            return new MessageManager(repository);
        }

        #endregion
    }
}
